﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.Modules;
using WP.Controls;
using WP.Controls.GridColumn;

using WP.RM.BusinessRule;
using WP.RM.BusinessLogical;
using WP.RM.DataAccess;

namespace WP.RM.Form
{
    public partial class frmRMProductBOMMtn : BaseMtn 
    {
        public frmRMProductBOMMtn()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));
            this.MtnTabControl = this.tbcMain;
            this.DesignTabsName = "tbpGeneral";
            tbcMain.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MinimumSize = this.Size;
        }
        public void ShowFromQry( string strRecID)
        {
            this.Show();
            this.Text = "产成品BOM单维护";
            this.RecID = Convert.ToInt64(strRecID );

        }

        #region Define Variable
        private bool mblnSettingStatus = false;
        private bool[] mDtlColumnReadOnlyArray;
        private bool[] mDtlColumnReadOnlyArray_LabourCost;
        private bool m_bCanTrigerCellValueChangedEven = false;
        private bool m_bCanTrigerCellValueChangedEven_LabourCost = false;
        private bool m_bSettingStatus = false;
        private bool m_bDtlChanged = false;
        private bool m_bDtlChanged_LabourCost = false;
        private string mstrWhereCondition = "";
        private frmWKParameter frmParameter = null; 
        private System.Windows.Forms.DataGridView.HitTestInfo mhtiDtl = null;
        private DBAccess mdbcon = new DBAccess(false, false);
        private enum DtlCol
        {
            RowSeqNo = 0,
            SeqNo,
            ProductFItemID,
            ProductName,
            TechnicsName,
            WKID,
            WKName,
            WKRemark,
            IsKeyWK,
            IsInputWK,
            CategoryID,
            CategoryName,
            SetID,
            SetName,
            FItemID,
            ItemNo,
            ItemName,
            SupNo,
            SupName,
            Price,
            PriceUnit,
            Qty,         //定额数量
            WastageRate, //损耗率 
            QtyWastage,  //损耗数量
            DetailCost,  //定额成本
            LabourCost,  //人工成本
            TotalCost,   //总成本     
            RecID,
            ValueChanged,
            DelButton
        }

        private enum LabourCostCol
        {
            RowSeqNo = 0,
            BOMSeqNo,
            SeqNo,
            WKID,
            WKName,
            WKRemark,
            IsKeyWK,
            CategoryID,
            CategoryName,
            SetID,
            SetName,
            ProductFItemID,
            ProductName,
            TechnicsName,
            FItemID,
            ItemNo,      //主要是用来计算这个工序要做的工作总量
            ItemName,
            CalUnit,
            CutType,
            WorkQty,     //总数量
            TotalQty,    //总加工计量数量( = WorkQty/ CutType )
            StandardQty, //10小时额定产量
            UsedHours,   //预计用工时间
            StandardWage,  // 固定工资
            StandardWage26, //26天标准工资
            UnitCost,        //记件工价
            WorkCost,    //工时费用标准
            TotWorkCost,  //工时费用
            Remark,         //备注
            RecID,
            ValueChanged,
            DelButton
        }

        #endregion

        #region ***Form Events

        private void frmRMProductBOMMtn_Load(object sender, EventArgs e)
        {
            this.TableName = "rmProductBOMHdr";
            frmParameter = new frmWKParameter(frmWKParameter.FromType.Product);
            pnlParameter.Enabled = false;
            //dgList.ColumnWidth = "0,70,180,100,40,20,120,90,130";
            dgList.ConnectionString = DBAccess.ConnectionDBString;
            dgList.TableName = this.TableName;
            dgList.ColumnWidth = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name);
            string strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            dgList.Sql = strSql;
            this.formStatus = FormStatus.Query;
            InitGridDtl();
            FillLookUpInfo();
            ShowOverViewGrid((this.CurrentMenuInfo.strOverViewCondition != "" && this.CurrentMenuInfo.strOverViewCondition != null ? " Where " : "") + this.CurrentMenuInfo.strOverViewCondition);

            frmParameter.TopMost = true;
            frmParameter.TopLevel = false;
            frmParameter.Dock = DockStyle.Fill;
            frmParameter.FormBorderStyle = FormBorderStyle.None;
            frmParameter.Show();
            pnlParameter.Controls.Add(frmParameter);
        }

        private bool  InitBOMHdr()
        {         
            DBAccess dbcon = new DBAccess(false, false);
            RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
            try
            {
                if (txtCategoryName.Text == "" || txtSetName.Text == "" || txtProductName.Text == "") return false ;
                
                string strSQL = "select * from rmProductBOMHdr where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}'";
                strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text);
                DataRow drRow = dbcon.GetDataFirstRow(strSQL);
                #region 检查 【类别系列BOM】是不是已被审核
                strSQL = " select * from rmCategorySetBOMHdr A where A.Approval=1";
                strSQL += " and A.CategoryID='{0}' and A.SetID='{1}'  ";
                strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text);
                DataRow drCheck = dbcon.GetDataFirstRow(strSQL);
                if (drCheck == null)
                {
                    MessageBox.Show("没有被审核 【类别系列BOM】", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false ;
                }
                #endregion

                if (!UpdateData()) return false;
                if (drRow == null)
                {
                    this.Cursor = Cursors.WaitCursor; 
                    dbcon.BeginTran();
                    string strProductFItemID = txtProductFItemID.Text;
                    if (rmBRL.InitProductBOMFromCategorySet(dbcon, strProductFItemID, txtCategoryID.Text, txtSetID.Text,txtTechnicsName.Text))
                        dbcon.CommitTran();
                    else
                        dbcon.RollbackTran();                    
                }
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                dbcon.RollbackTran(); 
            }
            this.Cursor = Cursors.Default;
            FillDtl(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
            FillDtl_LabourCost(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
            dbcon.CloseCon();
            return true;
        }

        private void ShowOverViewGrid()
        {
            ShowOverViewGrid("");
        }

        private void ShowOverViewGrid(string strWhereCondition)
        {
            string strSql = "";
            if (dgList.Sql.Trim() == "")
                strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            else
                strSql = dgList.Sql;

            if (strWhereCondition != "")
            {
                string strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
                strSql = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain) + " " + strWhereCondition;
                strSql += strOrderBy;
            }
            string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            mstrWhereCondition = strWhere;
            this.dgList.Sql = strSql;
        }
        private void frmRMProductBOMMtn_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgList);
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvBOM);
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvLabourCost);
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!this.UpdateData()) return;
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!this.DeleteData()) return;


        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab == this.tbpOverview)
                base.ExportToExcel(dgList);
            else
            {
                string strSQL = "";
                strSQL = "select * from rmProduct where recid ='" + this.m_lRecId + "'";
                DataRow drHdr = mdbcon.GetDataFirstRow(strSQL);
                if (drHdr == null) return;

                BOMToExcel.ToExcel_BOM(mdbcon, BOMToExcel.BOMType.ProductBOM, drHdr);
            }
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Bottom);
        }
        public override void SetNavigatorBarTooltip()
        {
            if (this.RecID <= 0)
            {
                this.btnBottom.ToolTipText ="定位到末页";
                this.btnTop.ToolTipText = "定位到首页";
                this.btnNext.ToolTipText ="定位到下一页";
                this.btnPrev.ToolTipText ="定位到前一页";
            }
            else
            {
                this.btnBottom.ToolTipText ="定位到末记录" ;
                this.btnTop.ToolTipText = "定位到首记录" ;
                this.btnNext.ToolTipText = "定位到下一条记录" ;
                this.btnPrev.ToolTipText = "定位到上一条记录" ;
            }
        }

        private void dgList_DefineColumn(object sender, EventArgs e)
        {
            base.SelectListViewField(dgList);
        }
        private void dgList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && dgList.CurrentRow != null && this.tbcMain.SelectedTab == tbpOverview )
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }
        private void dgList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgList.CurrentRow != null && BaseFunctions.IsDataGridCell(this.dgList, e))
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }

        protected override void Field_Leave(object sender, System.EventArgs e)
        {
            base.Field_Leave(sender, e);
            Control con = sender as Control;
            if (con == null) return;

            //below is some speci field , need do some speci work
            if (con.Name == txtCategoryName.Name)
            {
            }
            else if (con.Name == txtTechnicsName.Name)
            {
                if (this.formStatus == FormStatus.AddNew)
                {
                    InitBOMHdr(); 
                }
            }
        }
        protected override void Field_Change(object sender, EventArgs e)
        {
            base.Field_Change(sender, e);
            if (this.formStatus == FormStatus.Delete) return;
            Control con = sender as Control;
            if (con == null) return;

            //if (con.Name == txtProductName.Name)
            //{
            //    string strSQL = "select * from rmProduct where ";
            //}
        }
        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }

            bool blnRet = false;
            if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvBOM.Name))
            {
                blnRet = dgvBOM_KeyDownEvent(keyData);
            }
            else if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvLabourCost.Name))
            {
                blnRet = dgvLabourCost_KeyDownEvent(keyData);
            }
            if (!blnRet)
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            return blnRet;
        }
        private void tbcMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete) &&
                this.dgList.Rows.Count == 0 && e.TabPageIndex > 0)
            {
                e.Cancel = true;
                return;
            }

            if (e.TabPageIndex == 0)
            {
                if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                {
                    if (this.ConfirmChange())
                    {
                        if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (!this.UpdateData())
                            {
                                if (m_bTabPageNeedCancel)
                                    e.Cancel = true;

                                m_bTabPageNeedCancel = true;
                                return;
                            }
                        }
                    }
                    this.formStatus = FormStatus.Delete;
                }
                else if (this.formStatus == FormStatus.Query)
                {
                    this.formStatus = FormStatus.Delete;
                }
                this.dgList.RefreshData();
                this.dgList.Focus();
            }
            else if (e.TabPageIndex != 0 && this.formStatus != FormStatus.AddNew)
            {
                if (this.RecID == -1)
                    this.RecID = Convert.ToInt64(dgList.RecID);

                if (e.TabPage == tbpOtherCost && (this.dgvBOM.CurrentRow == null  || CvtFunc.ToString ( this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value )==""))
                {
                    this.tbcMain.SelectedTab = tbpBOM;
                }
            }

            else if (e.TabPageIndex == 2 && this.formStatus == FormStatus.AddNew)
            {
                if (this.formStatus == FormStatus.AddNew)
                {
                    e.Cancel = !InitBOMHdr();
                }
            }
            else if ((e.TabPage == tbpBOM || e.TabPage == tbpOtherCost) && this.formStatus == FormStatus.AddNew)
            {
                e.Cancel = !InitBOMHdr();
            }
        }
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

        #endregion Form Events***

        #region ***Form Functions

        public override bool UpdateData()
        {
            bool bUpdateResult = true;
            string strErrMsg = "";
            if (this.dgvBOM.CurrentRow != null)
            {
                this.dgvBOM.EndEdit();
                if (!CheckDtlRow(ref strErrMsg))
                {
                    MsgBoxEx.Show(strErrMsg, SysVar.WarnTitle);
                    return false;
                }
                else
                {
                    Update_Detail(this.dgvBOM.CurrentRow);
                }
            }
            if (this.dgvLabourCost.CurrentRow != null)
            {
                this.dgvLabourCost.EndEdit();
                if (!CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) != "")
                    {
                        MsgBoxEx.Show(strErrMsg, SysVar.WarnTitle);
                        return false;
                    }
                }
                else
                {
                    Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow);
                }
            }
            if (base.ConfirmChange())
            {
                bUpdateResult = base.UpdateData();
            }
            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            strErrPrompt = string.Empty;
            DBAccess dBAccess = new DBAccess(false, false);
            DataRow dr = base.GetCurrentMtnDataRow();

            RM.BusinessRule.RMProductBOMHdrBRL mBRL = new WP.RM.BusinessRule.RMProductBOMHdrBRL();
            bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            dBAccess.CloseCon();
            return bCheckResult;
        }

        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {
            string strSql = string.Empty;
            strSql = base.GetLookUpSQL(strTableName, strLookUpControlName);
            string strMainSQL = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain);
            string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            string strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
            if (strLookUpControlName == this.ubtCategoryName.Name)
            {
                strSql = base.GetLookUpSQL(strTableName, strLookUpControlName);

            }
            else if (strLookUpControlName == this.ubtSetName.Name)
            {

            }
            else if (strLookUpControlName == this.ubtProductName.Name)
            {
                if (strWhere == "")
                {
                    strWhere = " where 1=1 ";
                }
                if (txtCategoryName.Text != "")
                {
                    strWhere += " and CategoryName='" + txtCategoryName.Text + "' ";
                }
                if (txtSetName.Text != "")
                {
                    strWhere += " and SetName='" + txtSetName.Text + "'";
                }
                else
                {
                    return strSql;
                }
            }
            return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }

        protected override void ubtLookUp_Click(object sender, EventArgs e)
        {
            base.ubtLookUp_Click(sender, e);
            Control con = sender as Control;
            if (con.Name == ubtProductName.Name)
            {
                txtCategoryName.Text = DataFunctions.GetFieldValue("rmProduct", "CategoryName", "ProductFItemID='" + txtProductFItemID.Text + "'");
                txtSetName.Text = DataFunctions.GetFieldValue("rmProduct", "SetName", "ProductFItemID='" + txtProductFItemID.Text + "'");
                txtCategoryID.Text = DataFunctions.GetFieldValue("rmCategorySetBOMHdr", "CategoryID", "ProductFItemID='" + txtProductFItemID.Text + "'");
                txtSetID.Text = DataFunctions.GetFieldValue("rmCategorySetBOMHdr", "SetID", "ProductFItemID='" + txtProductFItemID.Text + "'"); ;

            }
        }
        public override void SetButtonStatus()
        {
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnTallyCalculate.Enabled = false;
                    this.FuntoolStripMenuItem.Enabled =  false ;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Delete:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = true ;
                    this.btnCancel.Enabled = false;
                    this.btnTallyCalculate.Enabled = false;
                    this.FuntoolStripMenuItem.Enabled = false ;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Query:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled  = true  ;
                    this.btnCancel.Enabled = false;
                    this.btnTallyCalculate.Enabled = false;
                    this.FuntoolStripMenuItem.Enabled = false;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Update:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnNew.Enabled = false ;
                    this.btnCancel.Enabled = true;
                    this.btnAddLine.Enabled = true;
                    this.btnTallyCalculate.Enabled = true;
                    this.FuntoolStripMenuItem.Enabled = true;
                    this.btnCopyTo.Enabled = true;
                    this.btnCopyBOMToLabour.Enabled = true;
                    break;
                case FormStatus.Loading:
                    break;

            }

            //this.btnToExcel.Visible = (this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query) && SysVar.AbleToExcel;
            this.btnToExcel.Visible = SysVar.AbleToExcel;
            //this.btnToExcel.Enabled = this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query;
            this.btnToExcel.Enabled = true ;

            newToolStripMenuItem.Enabled = btnNew.Enabled;
            cancelToolStripMenuItem.Enabled = btnCancel.Enabled;
            deleteToolStripMenuItem.Enabled = btnDelete.Enabled;
            saveToolStripMenuItem.Enabled = btnUpdate.Enabled;

            this.btnTop.Enabled = true;
            this.btnBottom.Enabled = true;
            this.btnPrev.Enabled = true;
            this.btnNext.Enabled = true;
            this.btnHelp.Enabled = true;
            this.btnExit.Enabled = true;
        }
        public override void SetOtherStatus()
        {
            mblnSettingStatus = true;

            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    this.txtProductName.Focus();
                    break;
                case FormStatus.Delete:
                    this.btnNew.Enabled = false;
                    break;
                case FormStatus.Query:
                    break;
                case FormStatus.Update:
                    this.btnNew.Enabled = true;
                    break;
                case FormStatus.Loading:
                    this.btnNew.Enabled = false;
                    break;
            }
            mblnSettingStatus = false;
        }

        private void ShowFormula(int intRow)
        {
            if (this.dgvBOM.Rows[intRow] == null) return;
            string strRecID = CvtFunc.ToString(this.dgvBOM.Rows[intRow].Cells[(int)DtlCol.RecID].Value);
            if (CvtFunc.ToDouble(strRecID) <= 0)
            {
                txtCalFormula.Text = "";
                return;
            }

            txtCalFormula.Text = DataFunctions.GetFieldValue(mdbcon, "rmWKProductFormula", "WKFormula", "BOMRecID='" + strRecID + "'");
        }

        protected override void ShowOtherData()
        {
            base.ShowOtherData();
            if (this.formStatus != FormStatus.Delete)
            {
                long lngRecID = CvtFunc.ToLong(DataFunctions.GetFieldValue("rmProduct", "RecID", "ProductFItemID='" + txtProductFItemID.Text + "'"));
                frmParameter.FillContent(lngRecID.ToString());
                InitGridDtl();
                FillDtl(txtCategoryID.Text, txtSetID.Text,txtProductFItemID.Text,txtTechnicsName.Text  );
                ShowLabourCost();
            }
            FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
            ShowWorkCost();
        }

        private void FillHdrData(string strCategoryID, string strSetID, string strProductFItemID, string strTechnicsName)
        {
            string strSQL = "select * from rmProductBOMHdr where CategoryID='{0}' and SetID='{1}' and ProductID='{2}' and TechnicsName='{3}' ";
            strSQL = string.Format(strSQL, strCategoryID, strSetID, strProductFItemID, strTechnicsName);
            DBAccess dbcon = new DBAccess(false, false);
            DataRow drHdr = dbcon.GetDataFirstRow(strSQL);
            if (drHdr != null)
            {
                //TotalLabourCost,TotalWastageCost,TotalDetailCost,TotalCost
                txtTotalDetailCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalDetailCost"], "Ns.2");
                txtTotalWastageCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalWastageCost"], "Ns.2");
                txtTotalLabourCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalLabourCost"], "Ns.2");
                txtTotalCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalCost"], "Ns.2");
                txtTotalWorkCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalWorkCost"], "Ns.2");
                txtStandardUnitCost.Text = BaseFunctions.FormatNumeric(drHdr["StandardUnitCost"], "Ns.2"); 
            }
        }

        public override void RefreshOverView()
        {
            base.RefreshOverView();
            if (this.RecID != -1)
                this.dgList.RecID = this.RecID;
        }

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("CategoryName", "rmCategory", "CategoryName", "ubtCategoryName");
            SetFieldLookUpInfo("SetName", "rmSet", "SetName", "ubtSetName");
            SetFieldLookUpInfo("ProductName", "rmProduct", "ProductName", "ubtProductName");

            SetFieldLookUpInfo("CategoryID", "rmCategory", "CategoryID", "ubtCategoryName");
            SetFieldLookUpInfo("SetID", "rmSet", "SetID", "ubtSetName");
            SetFieldLookUpInfo("ProductID", "rmProduct", "ProductID", "ubtProductName");
            SetFieldLookUpInfo("ProductFItemID", "rmProduct", "ProductFItemID", "ubtProductName");

        }

        #endregion Form Functions***


        #region Grid
        private void InitGridDtl()
        {
            // RowSeqNo = 0,SeqNo,WKName,WKRemark,CategoryName,SetName
            // IsKeyWK,  ItemNo, ItemName, Price, PriceUnit,
            // Qty, WastageRate, RatedCost,LabourCost, TotalCost,         
            this.dgvBOM.Columns.Clear();
            this.dgvBOM.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;
            colRowSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable ;

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;
            colSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colProductFItemID = new DataGridViewTextBoxColumn();
            colProductFItemID.HeaderText = "成品编码";
            colProductFItemID.Visible = false;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.Width = 50;
            colProductFItemID.ReadOnly = false;
            colProductFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colProductName = new TextLookUpColumn();
            colProductName.HeaderText = "产品名称";
            colProductName.Width = 150;
            colProductName.Name = "ProductName";
            colProductName.ReadOnly = false;
            colProductName.Visible = false;
            colProductName.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colTechnicsName = new TextLookUpColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Width = 150;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.ReadOnly = false;
            colTechnicsName.Visible = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colWKID = new DataGridViewListColumn();
            colWKID.HeaderText = "工序编号";
            colWKID.Width = 0;
            colWKID.Name = "WKID";
            colWKID.ReadOnly = true;
            colWKID.Visible = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 150;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = false;
            colWKName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colWKRemark = new DataGridViewListColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 0;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;
            colWKRemark.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;
            colCategoryID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryName = new DataGridViewListColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width = 80;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = false;
            colCategoryName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;
            colSetID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetName = new DataGridViewListColumn();
            colSetName.HeaderText = "系列名称";
            colSetName.Width = 80;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = false;
            colSetName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewCheckBoxColumn colKeyWK = new DataGridViewCheckBoxColumn();
            colKeyWK.HeaderText = "关键工序";
            colKeyWK.Width = 70;
            colKeyWK.Name = "isKeyWK";
            colKeyWK.ReadOnly = true;
            colKeyWK.Visible = false;
            colKeyWK.Resizable = DataGridViewTriState.False;
            colKeyWK.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewCheckBoxColumn colInputWK = new DataGridViewCheckBoxColumn();
            colInputWK.HeaderText = "投料工序";
            colInputWK.Width = 70;
            colInputWK.Name = "isInputWK";
            colInputWK.ReadOnly = true;
            colInputWK.Visible = false;
            colInputWK.Resizable = DataGridViewTriState.False;
            colInputWK.SortMode = DataGridViewColumnSortMode.NotSortable;

            //ItemNo, ItemName, Price, PriceUnit,Qty, WastageRate,
            DataGridViewTextBoxColumn colFItemID = new DataGridViewTextBoxColumn();
            colFItemID.HeaderText = "物料内码";
            colFItemID.Visible = false ;
            colFItemID.Width = 120;
            colFItemID.Name = "FItemID";
            colFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colItemNo = new TextLookUpColumn();
            colItemNo.HeaderText = "材料代码";
            colItemNo.Width = 100;
            colItemNo.Name = "ItemNo";
            colItemNo.ReadOnly = false;
            colItemNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "材料名称";
            colItemName.Visible = true;
            colItemName.Width = 120;
            colItemName.Name = "ItemName";
            colItemName.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colSupNo = new TextLookUpColumn();
            colSupNo.HeaderText = "供应商代码";
            colSupNo.Width = 100;
            colSupNo.Name = "SupNo";
            colSupNo.ReadOnly = false;
            colSupNo.Visible = false;
            colSupNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colSupName = new DataGridViewTextBoxColumn();
            colSupName.HeaderText = "供应商名称";
            colSupName.Visible = true;
            colSupName.Width = 120;
            colSupName.Visible = false;
            colSupName.Name = "SupName";
            colSupName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colPrice = new DataGridViewTextBoxColumn();
            colPrice.HeaderText = "单价";
            colPrice.Visible = true;
            colPrice.Width = 80;
            colPrice.Name = "Price";
            colPrice.SortMode = DataGridViewColumnSortMode.NotSortable;
            colPrice.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colPrice.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colPriceUnit = new DataGridViewTextBoxColumn();
            colPriceUnit.HeaderText = "单位";
            colPriceUnit.Visible = true;
            colPriceUnit.Width = 60;
            colPriceUnit.Name = "PriceUnit";
            colPriceUnit.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colQty = new DataGridViewTextBoxColumn();
            colQty.HeaderText = "定额数量";
            colQty.Width = 70;
            colQty.Visible = true;
            colQty.Name = "Qty";
            colQty.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWastageRate = new DataGridViewTextBoxColumn();
            colWastageRate.HeaderText = "损耗率%";
            colWastageRate.Visible = true;
            colWastageRate.Width = 50;
            colWastageRate.Name = "WastageRate";
            colWastageRate.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWastageRate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            // QtyWastage,DetailCost,LabourCost, TotalCost,
            DataGridViewTextBoxColumn colQtyWastage = new DataGridViewTextBoxColumn();
            colQtyWastage.HeaderText = "损耗数量";
            colQtyWastage.Visible = false;
            colQtyWastage.Width = 70;
            colQtyWastage.Name = "QtyWastage";
            colQtyWastage.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQtyWastage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQtyWastage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailCost = new DataGridViewTextBoxColumn();
            colDetailCost.HeaderText = "定额成本";
            colDetailCost.Visible = true;
            colDetailCost.Width = 70;
            colDetailCost.Name = "DetailCost";
            colDetailCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colDetailCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colLabourCost = new DataGridViewTextBoxColumn();
            colLabourCost.HeaderText = "人工成本";
            colLabourCost.Visible = false ;
            colLabourCost.Width = 70;
            colLabourCost.Name = "LabourCost";
            colLabourCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colLabourCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colLabourCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotalCost = new DataGridViewTextBoxColumn();
            colTotalCost.HeaderText = "总单价";
            colTotalCost.Visible = true;
            colTotalCost.Width = 80;
            colTotalCost.Name = "TotalCost";

            colTotalCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalCost.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            colItemName.ReadOnly = true;
            colSupNo.ReadOnly = true;
            colSupName.ReadOnly = true;

            this.dgvBOM.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo, colSeqNo, colProductFItemID , colProductName,colTechnicsName,colWKID  ,colWKName,
                                                                    colWKRemark, colKeyWK, colInputWK, colCategoryID   ,colCategoryName, colSetID ,colSetName ,
                                                                    colFItemID, colItemNo, colItemName,colSupNo,colSupName , colPrice, colPriceUnit,colQty, colWastageRate,
                                                                    colQtyWastage,colDetailCost,colLabourCost, colTotalCost,
                                                                    colRecID, colValueChanged, colDel });

            mDtlColumnReadOnlyArray = new bool[dgvBOM.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvBOM.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvBOM.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvBOM.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvBOM.Columns.Count) dgvBOM.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }
            
            this.dgvBOM.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvBOM.RowTemplate.Height = 20;
            this.dgvBOM.RowHeadersWidth = 23;
            this.dgvBOM.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvBOM.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvBOM.ColumnHeadersHeight = 30;
            this.dgvBOM.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvBOM.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvBOM.AllowUserToResizeRows = false;

        }
        private void InitGridDtlLabourCost()
        {
           
            //RowSeqNo =0,
            //SeqNo,WKName,WKRemark,CategoryName , SetName  ,ProductName     ,ItemNo                  
            this.dgvLabourCost.Columns.Clear();
            this.dgvLabourCost.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colHdrSeqNo = new DataGridViewTextBoxColumn();
            colHdrSeqNo.HeaderText = "BOM序号";
            colHdrSeqNo.Visible = false;
            colHdrSeqNo.Name = "BOMSeqNo";
            colHdrSeqNo.Width = 50;
            colHdrSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;

            DataGridViewListColumn colWKID = new DataGridViewListColumn();
            colWKID.HeaderText = "工序编号";
            colWKID.Width = 0;
            colWKID.Name = "WKID";
            colWKID.ReadOnly = true;
            colWKID.Visible = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 150;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = false;

            DataGridViewListColumn colWKRemark = new DataGridViewListColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 0;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;

            DataGridViewCheckBoxColumn colKeyWK = new DataGridViewCheckBoxColumn();
            colKeyWK.HeaderText = "关键工序";
            colKeyWK.Width = 70;
            colKeyWK.Name = "isKeyWK";
            colKeyWK.ReadOnly = false ;
            colKeyWK.Resizable = DataGridViewTriState.False;
            colKeyWK.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;

            DataGridViewListColumn colCategoryName = new DataGridViewListColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width = 80;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = false;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;

            DataGridViewListColumn colSetName = new DataGridViewListColumn();
            colSetName.HeaderText = "系列名称";
            colSetName.Width = 80;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = false;

            DataGridViewListColumn colProductFItemID = new DataGridViewListColumn();
            colProductFItemID.HeaderText = "产成品编码";
            colProductFItemID.Width = 80;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.ReadOnly = false;
            colProductFItemID.Visible = false;

            DataGridViewListColumn colProductName = new DataGridViewListColumn();
            colProductName.HeaderText = "产成品名称";
            colProductName.Width = 80;
            colProductName.Name = "ProductName";
            colProductName.ReadOnly = false;
            colProductName.Visible = false;

            DataGridViewListColumn colTechnicsName = new DataGridViewListColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Width = 150;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.ReadOnly = false;
            colTechnicsName.Visible = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colFItemID = new DataGridViewTextBoxColumn();
            colFItemID.HeaderText = "物料内码";
            colFItemID.Visible = false ;
            colFItemID.Width = 120;
            colFItemID.Name = "FItemID";
            colFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colItemNo = new TextLookUpColumn();
            colItemNo.HeaderText = "物料代码";
            colItemNo.Width = 80;
            colItemNo.Name = "ItemNo";
            colItemNo.ReadOnly = false;
            colItemNo.Visible = true ;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "物料名称";
            colItemName.Visible = true ;
            colItemName.Name = "ItemName";
            colItemName.Width = 50;
            colItemName.ReadOnly = false;

            //CalUnit,CutType,WorkQty, TotalQty,    //总数量            
            TextLookUpColumn colCalUnit = new TextLookUpColumn();
            colCalUnit.HeaderText = "计件单位";
            colCalUnit.Width = 100;
            colCalUnit.Name = "CalUnit";
            colCalUnit.ReadOnly = false;

            TextLookUpColumn colCutType = new TextLookUpColumn();
            colCutType.HeaderText = "分切系数";
            colCutType.Visible = true;
            colCutType.Width = 70;
            colCutType.Name = "CutType";

            DataGridViewTextBoxColumn colWorkQty = new DataGridViewTextBoxColumn();
            colWorkQty.HeaderText = "总数量";
            colWorkQty.Width = 70;
            colWorkQty.Visible = true;
            colWorkQty.Name = "WorkQty";
            colWorkQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotalQty = new DataGridViewTextBoxColumn();
            colTotalQty.HeaderText = "计量数量";
            colTotalQty.Width = 60;
            colTotalQty.Visible = true ;
            colTotalQty.Name = "TotalQty";
            colTotalQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            //StandardQty, //10小时额定产量
            //spendHours,   //预计用工时间
            //StandardWage,  // 固定工资          
            DataGridViewTextBoxColumn colStandardQty = new DataGridViewTextBoxColumn();
            colStandardQty.HeaderText = "额定产量(10小时)";
            colStandardQty.Visible = true;
            colStandardQty.Width = 50;
            colStandardQty.Name = "StandardQty";

            DataGridViewTextBoxColumn colSpendHours = new DataGridViewTextBoxColumn();
            colSpendHours.HeaderText = "耗用工时";
            colSpendHours.Visible = true ;
            colSpendHours.Width = 45;
            colSpendHours.Name = "SpendHours";
            colSpendHours.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colSpendHours.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colStandardWage = new DataGridViewTextBoxColumn();
            colStandardWage.HeaderText = "固定工资";
            colStandardWage.Visible = true;
            colStandardWage.Width = 70;
            colStandardWage.Name = "StandardWage";
            colStandardWage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            //StandardWage26, //26天标准工资
            //UnitCost,        //记件工价
            //Remark,         //备注 
            DataGridViewTextBoxColumn colStandardWage26 = new DataGridViewTextBoxColumn();
            colStandardWage26.HeaderText = "标准工资(26天)";
            colStandardWage26.Visible = true;
            colStandardWage26.Width = 60;
            colStandardWage26.Name = "StandardWage26";
            colStandardWage26.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage26.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colUnitCost = new DataGridViewTextBoxColumn();
            colUnitCost.HeaderText = "记件工价";
            colUnitCost.Visible = true ;
            colUnitCost.Width = 65;
            colUnitCost.Name = "UnitCost";
            colUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWorkCost = new DataGridViewTextBoxColumn();
            colWorkCost.HeaderText = "工时费用标准";
            colWorkCost.Visible = true ;
            colWorkCost.Width = 60;
            colWorkCost.Name = "WorkCost";
            colWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailTotWorkCost = new DataGridViewTextBoxColumn();
            colDetailTotWorkCost.HeaderText = "工时费用";
            colDetailTotWorkCost.Visible = true ;
            colDetailTotWorkCost.Width = 60;
            colDetailTotWorkCost.Name = "DetailTotWorkCost";
            colDetailTotWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailTotWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;


            DataGridViewTextBoxColumn colRemark = new DataGridViewTextBoxColumn();
            colRemark.HeaderText = "备注";
            colRemark.Visible = true;
            colRemark.Width = 80;
            colRemark.Name = "Remark";
            colRemark.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colRemark.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            //RowSeqNo =0,
            //SeqNo,WKName,WKRemark,CategoryName , SetName   
            //CalUnit,CutType, TotalQty,    //总数量 
            //StandardQty, //10小时额定产量
            //spendHours,   //预计用工时间
            //StandardWage,  // 固定工资   
            //StandardWage26, //26天标准工资
            //UnitCost,        //记件工价
            //Remark,         //备注 
            this.dgvLabourCost.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo,colHdrSeqNo, colSeqNo, colWKID  ,colWKName, colWKRemark,colKeyWK, colCategoryID ,colCategoryName, colSetID ,colSetName , 
                                                                    colProductFItemID,  colProductName,colTechnicsName,colFItemID,colItemNo , colItemName ,
                                                                    colCalUnit , colCutType  , colWorkQty  ,colTotalQty , colStandardQty  ,colSpendHours, colStandardWage  ,
                                                                    colStandardWage26, colUnitCost,colWorkCost,colDetailTotWorkCost , colRemark ,
                                                                    colRecID, colValueChanged, colDel  });

            mDtlColumnReadOnlyArray_LabourCost = new bool[dgvLabourCost.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvLabourCost.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvLabourCost.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray_LabourCost[i] = dgvLabourCost.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvLabourCost.Columns.Count) dgvLabourCost.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvLabourCost.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvLabourCost.RowTemplate.Height = 20;
            this.dgvLabourCost.RowHeadersWidth = 23;
            this.dgvLabourCost.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvLabourCost.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvLabourCost.ColumnHeadersHeight = 40;
            this.dgvLabourCost.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvLabourCost.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvLabourCost.AllowUserToResizeRows = false;

        }

        private void AddDtlRow(string strGridName)
        {
            AddDtlRow(strGridName, -1);
        }

        private void RefershRowSeqNo( string strGridName)
        {
            DBAccess dbCon = new DBAccess(false, false);
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                foreach (DataGridViewRow dgvRow in this.dgvBOM.Rows)
                {
                    string strErrMsg = "";
                    dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                    if (this.dgvBOM.CurrentRow.Index < dgvRow.Index)
                    {
                        if (CvtFunc.ToDouble(dgvRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            string strSQL = "update rmProductBOMDetail set RowSeqNo='" + (dgvRow.Index + 1) + "' where RecID='" + dgvRow.Cells[(int)DtlCol.RecID].Value + "'";
                            dbCon.ExecuteSql(strSQL);
                        }
                    }
                }
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
                {
                    string strErrMsg = "";
                    dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                    if (this.dgvLabourCost.CurrentRow.Index < dgvRow.Index)
                    {
                        if (CvtFunc.ToDouble(dgvRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                        {
                            string strSQL = "update rmProductBOMLabourCost set RowSeqNo='" + (dgvRow.Index + 1) + "' where RecID='" + dgvRow.Cells[(int)LabourCostCol.RecID].Value + "'";
                            dbCon.ExecuteSql(strSQL);
                        }
                    }
                }
            }
            dbCon.CloseCon(); 
        }

        private void AddDtlRow(string strGridName, double iRow)
        {
            if (strGridName == dgvBOM.Name)
            {
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvBOM.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvBOM.Rows.Add();
                    intRow = this.dgvBOM.Rows.Count - 1;
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmProductBOMDetail", "max(SeqNo)", "CategoryID='" + txtCategoryID.Text + "' and SetID='" + txtSetID.Name + "' and TechnicsName='"+ txtTechnicsName.Text +"'")) + 1);
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ProductFItemID].Value = txtProductFItemID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ProductName].Value = txtProductName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.TechnicsName].Value = txtTechnicsName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.CategoryID].Value = txtCategoryID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.CategoryName].Value = txtCategoryName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SetID].Value = txtSetID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SetName].Value = txtSetName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.IsKeyWK].Value = "false";
                if (dgvBOM.Rows.Count > 0 && intRow >= 1)
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKID].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKID].Value;
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKRemark].Value;
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKName].Value;
                }
                else
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKID].Value = "";
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = "";
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName].Value = "";
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.FItemID].Value = "0";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ItemNo].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ItemName].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.LabourCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.Price].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.PriceUnit].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.Qty].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.QtyWastage].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.DetailCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.TotalCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.WastageRate].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.RecID].Value = -1;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvBOM.CurrentCell = dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName];
                m_bCanTrigerCellValueChangedEven = true;               
            }
            else if (strGridName == this.dgvLabourCost.Name)
            {
                if (dgvBOM.Rows.Count == 0) return;
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven_LabourCost = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvLabourCost.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvLabourCost.Rows.Add();
                    intRow = this.dgvLabourCost.Rows.Count - 1;
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RowSeqNo].Value = dgvLabourCost.Rows.Count.ToString();

                string strBOMSeqNo = "0";
                string strItemNo ="";
                if (  dgvBOM.CurrentRow !=null )
                {
                    strBOMSeqNo = CvtFunc.ToString(dgvBOM.CurrentRow.Cells[(int)DtlCol.SeqNo].Value);
                    strItemNo = CvtFunc.ToString(dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.BOMSeqNo].Value = strBOMSeqNo ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ItemNo].Value = "" ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ItemName].Value ="";

                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmProductBOMLabourCost", "max(SeqNo)", "CategoryID='" + txtCategoryID.Text + "' and SetID='" + txtSetID.Name + "' and ProductFItemID='"+ txtProductFItemID.Text + "' and TechnicsName='" + txtTechnicsName.Text + "'")) + 1);
                
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CategoryID].Value = txtCategoryID.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SetID].Value = txtSetID.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ProductFItemID].Value = txtProductFItemID.Text;
                
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CategoryName].Value = txtCategoryName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SetName].Value = txtSetName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ProductName].Value = txtProductName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TechnicsName].Value = txtTechnicsName.Text;
               
                //if (dgvLabourCost.Rows.Count > 0 && intRow >=1)
                //{

                //    dgvLabourCost.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = dgvLabourCost.Rows[intRow-1].Cells[(int)DtlCol.WKRemark].Value;
                //    dgvLabourCost.Rows[intRow].Cells[(int)DtlCol.WKName].Value = dgvLabourCost.Rows[intRow-1].Cells[(int)DtlCol.WKName].Value;
                //}
                //else
                {
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKRemark].Value = "";
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKName].Value = "";
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CalUnit].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CutType].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardWage].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardWage26].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TotalQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.UnitCost].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.UsedHours].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TotalQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.Remark].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RecID].Value = -1;
                this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = false ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ValueChanged].Value = "0";
                dgvLabourCost.CurrentCell = dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKName];
                m_bCanTrigerCellValueChangedEven_LabourCost = true;
            }
            RefershRowSeqNo(strGridName );
        }

        private bool CheckDtlRow(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvBOM.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlRow_LabourCost(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvLabourCost.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell_LabourCost(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlCell(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvBOM.CurrentRow != null && this.dgvBOM.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvBOM.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((DtlCol)iColumn)
            {
                case DtlCol.WKID :
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序编码不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureID"))
                    {
                        strErrMsg = "不存在的工序编码";
                        return false;
                    }
                    return true;
                case DtlCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
                case DtlCol.ItemNo:
                    if (strValue.Trim() == "" && CvtFunc.ToBoolean(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.IsInputWK].Value))
                    {
                        strErrMsg = "投料工序的物料名称不能为空";
                        return false;
                    }
                    else if (!DataFunctions.CheckRecordExist("iminvmaster", strValue, "ItemNo") && strValue != "")
                    {
                        strErrMsg = "不存在的物料编码";
                        return false;
                    }
                    return true;
            }
            return bReturnValue;
        }
        private bool CheckDtlCell_LabourCost(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvLabourCost.CurrentRow != null && this.dgvLabourCost.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvLabourCost.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((LabourCostCol)iColumn)
            {
                case LabourCostCol.WKID:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序编码不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureID"))
                    {
                        strErrMsg = "不存在的工序编码";
                        return false;
                    }
                    return true;
                case LabourCostCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
                case LabourCostCol.ItemNo:
                    //if (strValue.Trim() == "" && CvtFunc.ToBoolean(this.dgvLabourCost.CurrentRow.Cells[(int)DtlCol.IsInputWK].Value))
                    //{
                    //    strErrMsg = "投料工序的物料名称不能为空";
                    //    return false;
                    //}
                    //else
                    if (!DataFunctions.CheckRecordExist("iminvmaster", strValue, "ItemNo") && strValue != "")
                    {
                        strErrMsg = "不存在的物料编码";
                        return false;
                    }
                    return true;
            }
            return bReturnValue;
        }

        private void btnAddLine_Click(object sender, EventArgs e)
        {
            string strErrMsg = string.Empty;
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                if (this.dgvBOM.Rows.Count == 0)
                {
                    AddDtlRow(this.dgvBOM.Name);
                }
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (Update_Detail(this.dgvBOM.CurrentRow))
                    {
                        AddDtlRow(this.dgvBOM.Name, dgvBOM.CurrentCell.RowIndex);
                        RefershRowSeqNo( this.dgvBOM.Name );
                    }
                }
                else if (string.IsNullOrEmpty(strErrMsg))
                {
                    MessageBox.Show(strErrMsg, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {                
                if (this.dgvLabourCost.Rows.Count == 0)
                {
                    AddDtlRow(this.dgvLabourCost.Name);
                }
                else if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow))
                    {
                        AddDtlRow(this.dgvLabourCost.Name, dgvLabourCost.CurrentCell.RowIndex);
                    }
                }
                else if (!string.IsNullOrEmpty(strErrMsg))
                {
                    MessageBox.Show(strErrMsg, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private bool Update_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                dbcon.BeginTran();
                RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
                DataRow drBOM = dbcon.GetDataSet("select * from rmProductBOMDetail").Tables[0].NewRow();
                dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                BaseFunctions.FillDataRowByGridRow(dgvRow, drBOM);
                drBOM["CategoryID"] = txtCategoryID.Text;
                drBOM["SetID"] = txtSetID.Text;
                drBOM["ProductFItemID"] = txtProductFItemID.Text;
                if (rmBRL.UpdateDetailValid(dbcon, drBOM))
                {
                    dbcon.CommitTran();
                }
                else
                {
                    dbcon.RollbackTran();
                }

                dgvRow.Cells[(int)DtlCol.RecID].Value = CvtFunc.ToString(drBOM["RecID"]);
                dgvRow.Cells[(int)DtlCol.Qty].Value =  BaseFunctions.FormatNumeric( CvtFunc.ToDouble  ( drBOM["Qty"]).ToString ("f8")  ,"Ns.8");  
                dgvRow.Cells[(int)DtlCol.DetailCost].Value = BaseFunctions.FormatNumeric(drBOM["DetailCost"], "Ns.4");
                dgvRow.Cells[(int)DtlCol.TotalCost].Value = BaseFunctions.FormatNumeric(drBOM["TotalCost"], "Ns.4");
                dgvRow.Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvBOM.EndEdit();
                this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
                FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text );
            }
            catch (Exception ex)
            {
                MsgBoxEx.Show(ex.ToString());
                dbcon.RollbackTran();
                return false;
            }
            dbcon.CloseCon();
            return true;
        }
        private bool Update_Detail_LabourCost(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            try
            {

                dbcon.BeginTran();
                RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
                DataRow drLabourCost = dbcon.GetDataSet("select top 0 * from rmProductBOMLabourCost").Tables[0].NewRow();
                dgvRow.Cells[(int)LabourCostCol.RowSeqNo].Value = dgvRow.Index + 1;
                BaseFunctions.FillDataRowByGridRow(dgvRow, drLabourCost);
                drLabourCost["CategoryID"] = txtCategoryID.Text;
                drLabourCost["SetID"] = txtSetID.Text;
                drLabourCost["ProductFItemID"] = txtProductFItemID.Text;
                if (rmBRL.UpdateDetailValid_LabourCost(dbcon, drLabourCost))
                {
                    dbcon.CommitTran();
                }
                else
                {
                    dbcon.RollbackTran();
                }

                dgvRow.Cells[(int)LabourCostCol.RecID].Value = CvtFunc.ToString(drLabourCost["RecID"]);
                dgvRow.Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(drLabourCost["TotalQty"], "Ns.2");
                dgvRow.Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(drLabourCost["UnitCost"], "Ns.6");
                dgvRow.Cells[(int)LabourCostCol.UsedHours].Value = BaseFunctions.FormatNumeric(drLabourCost["SpendHours"], "Ns.2");
                dgvRow.Cells[(int)LabourCostCol.TotWorkCost].Value = BaseFunctions.FormatNumeric(drLabourCost["DetailTotWorkCost"], "Ns.2");
                dgvRow.Cells[(int)LabourCostCol.ValueChanged].Value = "0";
                this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
                dgvLabourCost.EndEdit();
                FillHdrData( txtCategoryID.Text , txtSetID.Text,txtProductFItemID.Text,txtTechnicsName.Text  );
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran();
                return false;
            }
            dbcon.CloseCon();
            return true;
        }

        public override bool DeleteData()
        {
            try
            {
                if (MessageBox.Show("您确实要删除此条信息？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    mdbcon.BeginTran();
                    string strSQL = "Select * from rmProductBOMHdr where  CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}'";
                    strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text );
                    DataRow drHdr = mdbcon.GetDataFirstRow(strSQL);
                    if (drHdr != null)
                    {
                        strSQL = " delete dbo.rmProductBOMDetail where  CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}' ";
                        strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = " delete dbo.rmProductBOMLabourCost where  CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}'";
                        strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = "delete dbo.rmWKProductFormula where BOMRecID in ( select RecID from rmProductBOMHdr where ProductFItemID ='{0}' and TechnicsName='{1}')";
                        strSQL = string.Format(strSQL, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = " delete dbo.rmWKFormulaOtherProductBOM where BOMRecID in ( select RecID from rmProductBOMHdr where ProductFItemID ='{0}' and TechnicsName='{1}')";
                        strSQL = string.Format(strSQL, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = " delete dbo.rmProductBOMHdr where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}'  and TechnicsName='{3}'";
                        strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);
                    }
                    mdbcon.CommitTran();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                mdbcon.RollbackTran();
                return false;
            }
            

            if (true)
            {
                this.formStatus = FormStatus.Delete;
                this.RecID = -1;
                this.formStatus = FormStatus.Delete;
            }

            return true;
        }

        private bool Delete_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
            DBAccess dbcon = new DBAccess ( false, false );
            string strRecID= CvtFunc.ToString ( dgvRow.Cells[(int)DtlCol.RecID].Value );
            if (rmBRL.DeleteDetailValid(dbcon, strRecID))
            {
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.DeleteDetailBOM(dbcon, strRecID);
            }
            return true;
        }

        private bool Delete_Detail_LabourCost(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
            DBAccess dbcon = new DBAccess(false, false);
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)LabourCostCol.RecID].Value);
            if (rmBRL.DeleteDetailValid_LabourCost(dbcon, strRecID))
            {
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.DeleteDetail_LabourCost(dbcon, strRecID);
            }
            return true;
        }

        private void FillDtl(string strCategoryID, string strSetID, string strProductFItemID, string strTechnicsName)
        {
            //InitBOMHdr();
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven = false;

            this.dgvBOM.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            strSql = "select A.* from rmProductBOMDetail A  where A.CategoryID='{0}' and A.SetID='{1}' and A.ProductFItemID='{2}' and A.TechnicsName='{3}' order by A.RowSeqNo,A.SeqNo";
            strSql = string.Format(strSql, strCategoryID, strSetID, strProductFItemID, strTechnicsName);
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];
            for (int i = 0; i < mUserAlertTable.Rows.Count; i++)
            {
                DataRow dr = mUserAlertTable.Rows[i];
                if (this.dgvBOM.Rows.Count <= i) this.dgvBOM.Rows.Add();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SeqNo].Value = dr["SeqNo"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKID].Value = dr["WKID"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue (dbCon,"rmWorkingProcedure","WorkingProcedureName","WorkingProcedureID='"+ dr["WKID"] +"'")  ;
                
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ProductFItemID].Value = dr["ProductFItemID"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetID].Value = dr["SetID"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryID].Value = dr["CategoryID"].ToString();

                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ProductName].Value = DataFunctions.GetFieldValue(dbCon, "rmProduct", "ProductName", "ProductFItemID='" + dr["ProductFItemID"] + "'");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.TechnicsName].Value = dr["TechnicsName"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryName].Value = DataFunctions.GetFieldValue(dbCon, "rmCategory", "CategoryName", "CategoryID='" + dr["CategoryName"] + "'");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetName].Value = DataFunctions.GetFieldValue(dbCon, "rmSet", "SetName", "SetID='" + dr["SetID"] + "'");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.FItemID].Value = CvtFunc.ToString(dr["FItemID"]);

                strSql = "select ItemNo,ItemName from iminvmaster where FItemID='" + CvtFunc.ToString(dr["FItemID"]) + "'";
                DataRow drItemNo = mdbcon.GetDataFirstRow(strSql);
                if (drItemNo == null)
                {

                }
                else
                {
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ItemNo].Value = CvtFunc.ToString(drItemNo["ItemNo"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ItemName].Value = CvtFunc.ToString(drItemNo["ItemName"]);
                }
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.LabourCost].Value = BaseFunctions.FormatNumeric(dr["LabourCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.Price].Value = BaseFunctions.FormatNumeric(dr["Price"], "Ns.3");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.PriceUnit].Value = CvtFunc.ToString(dr["PriceUnit"]);
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.Qty].Value = BaseFunctions.FormatNumeric(CvtFunc.ToDouble(dr["Qty"]).ToString("F8"), "Ns.8");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.QtyWastage].Value = BaseFunctions.FormatNumeric(dr["QtyWastage"], "Ns.2");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WastageRate].Value = BaseFunctions.FormatNumeric(dr["WastageRate"], "Ns.2");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.TotalCost].Value = BaseFunctions.FormatNumeric(dr["TotalCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.DetailCost].Value = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsKeyWK].Value = dr["IsKeyWK"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsInputWK].Value = dr["IsInputWK"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SupNo].Value = dr["SupNo"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SupName].Value = dr["SupName"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ValueChanged].Value = "0";
                this.dgvBOM.EndEdit();
            }//
           
            dbCon.CloseCon();
            base.SetBlankImage(dgvBOM);
            RefershRowSeqNo(this.dgvBOM.Name); 
            m_bCanTrigerCellValueChangedEven = true;
        }

        private void FillDtl_LabourCost(string strCategoryID, string strSetID, string strProductFItemID, string strTechnicsName)
        {
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven_LabourCost = false;

            this.dgvLabourCost.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            strSql = "select A.* from rmProductBOMLabourCost A  where A.CategoryID='" + strCategoryID + "' and A.SetID='" + strSetID + "' and A.ProductFItemID='" + strProductFItemID + "' and A.TechnicsName='" + strTechnicsName + "' order by A.RowSeqNo,A.seqno";
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];
            foreach (DataRow dr in mUserAlertTable.Rows)
            {
                this.dgvLabourCost.Rows.Add();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.RowSeqNo].Value = dgvLabourCost.Rows.Count.ToString();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.BOMSeqNo].Value = dr["BOMSeqNo"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SeqNo].Value = dr["SeqNo"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKID].Value = dr["WKID"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue ( dbCon,"rmWorkingProcedure","WorkingProcedureName","WorkingProcedureID ='"+ dr["WKID"] +"'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKRemark].Value = dr["WKRemark"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.IsKeyWK].Value = dr["IsKeyWK"].ToString().TrimEnd();
                
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CategoryID].Value = dr["CategoryID"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SetID].Value = CvtFunc.ToString(dr["SetID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ProductFItemID].Value = CvtFunc.ToString(dr["ProductFItemID"]);

                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CategoryName].Value = DataFunctions.GetFieldValue(dbCon, "rmCategory", "CategoryName", " CategoryID='" + dr["CategoryID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SetName].Value = DataFunctions.GetFieldValue(dbCon, "rmSet", "SetName", " SetID='" + dr["SetID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ProductName].Value = DataFunctions.GetFieldValue(dbCon, "rmProduct", "ProductName", " ProductFItemID='" + dr["ProductFItemID"] + "'");
                
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TechnicsName].Value = CvtFunc.ToString(dr["TechnicsName"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.FItemID].Value = CvtFunc.ToString(dr["FItemID"]);
                strSql = "select ItemNo,ItemName from iminvmaster where FItemID='" + CvtFunc.ToString(dr["FItemID"]) + "'";
                DataRow drItemNo = mdbcon.GetDataFirstRow(strSql);
                if (drItemNo == null)
                {

                }
                else
                {
                    dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemNo].Value = CvtFunc.ToString(drItemNo["ItemNo"]);
                    dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemName].Value = CvtFunc.ToString(drItemNo["ItemName"]);
                }
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CalUnit].Value = CvtFunc.ToString(dr["CalUnit"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CutType].Value = CvtFunc.ToString(dr["CutType"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.Remark].Value = CvtFunc.ToString(dr["Remark"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(dr["StandardQty"], "Ns.3");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardWage].Value = CvtFunc.ToString(dr["StandardWage"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardWage26].Value = BaseFunctions.FormatNumeric(dr["StandardWage26"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WorkQty].Value = BaseFunctions.FormatNumeric(dr["WorkQty"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(dr["TotalQty"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(dr["UnitCost"], "Ns.6");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dr["WorkCost"], "Ns.4");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotWorkCost].Value = BaseFunctions.FormatNumeric(dr["DetailTotWorkCost"], "Ns.2"); 
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.UsedHours].Value = BaseFunctions.FormatNumeric(dr["SpendHours"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ValueChanged].Value = "0";
            }

            if (dgvLabourCost.Rows.Count == 0)
            {
                AddDtlRow(this.dgvLabourCost.Name);
            }
            dbCon.CloseCon();
            base.SetBlankImage(dgvLabourCost);
            m_bCanTrigerCellValueChangedEven_LabourCost = true;
        }

        private void ShowLabourCost()
        {
            InitGridDtlLabourCost();
            FillDtl_LabourCost(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text );
        }

        private void dgvBOM_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvBOM.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvBOM.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex,this.dgvBOM.Name  );
                }
            }
            else
            {
                if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvBOM, e))
                {
                    this.dgvBOM.CurrentCell.Selected = true;
                    this.dgvBOM.CurrentCell.Selected = false;
                    if (!this.Delete_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvBOM.Rows.Remove(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]);
                    if (this.dgvBOM.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvBOM.Name);
                    }
                }
            }
        }

        private void dgvLabourCost_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvLabourCost.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvLabourCost.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex, this.dgvLabourCost.Name  );
                }
            }
            else
            {
                if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvLabourCost, e))
                {
                    this.dgvLabourCost.CurrentCell.Selected = true;
                    this.dgvLabourCost.CurrentCell.Selected = false;
                    if (!this.Delete_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvLabourCost.Rows.Remove(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]);
                    if (this.dgvLabourCost.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvLabourCost.Name);
                    }
                }
            }
        }

        private void 可更改工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "", strGridName = "", strWKID = ""; ;
            int intCol = 0;

            if (this.tbcMain.SelectedTab == tbpBOM)
                strWKID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID]);
            else
                strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)DtlCol.WKID]); 
            
            strSQL = " select A.CategoryID as 类别编码, A.CategoryName as 类别名称,A.WKProductID as 工序编码,A.WKName as 工序名称,A.RecID from rmCategoryWKAlter A inner join rmCategoryWK B on a.hdrseqno=b.seqno where B.CategoryID='" + txtCategoryID.Text + "' and B.WKProductID='" + strWKID + "' ";
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName = this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WkName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "可更改工序ToolStripMenuItem", strGridName);
        }

        private void 所有工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "", strGridName = "";
            int intCol = 0;
            strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorkingProcedure");
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName= this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WorkingProcedureName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "所有工序ToolStripMenuItem", strGridName);
        }

        private void 类别工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "", strGridName = "";
            int intCol = 0;
            strSQL = "select RecID, WKProductID as 工序编码,WKName as 工序名称 from rmCategoryWK where categoryID='" + txtCategoryID.Text + "' order by WKName";
            strCaption = "类别工序选择";
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName = this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WkName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "类别工序ToolStripMenuItem", strGridName);
        }

        private void Dtl_LookUp(int iColumnIndex,string strGridName)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            if (strGridName == this.dgvBOM.Name)
            {
                switch ((DtlCol)iColumnIndex)
                {
                    case DtlCol.WKName:
                        cmsWKLookup.Show(this.ActiveControl, new Point(this.ActiveControl.Top, this.ActiveControl.Left));
                        break;                        
                    case DtlCol.ItemNo:
                        strSQL = BaseFunctions.GetLookUpSQL("iminvmaster"); //" select ItemNo,ItemName,SupNo,SupName,MarketCost,CostUnit from iminvmaster where ClosedStatus=0 order by itemno";
                        strCaption = "物料选择";
                        if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value != null) strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value.ToString();
                        strFindField = "ItemNo";
                        break;
                }
            }
            else if (strGridName == this.dgvLabourCost.Name)
            {
                switch ((LabourCostCol)iColumnIndex)
                {
                    case LabourCostCol.WKName:

                        cmsWKLookup.Show(this.ActiveControl, new Point(this.ActiveControl.Top, this.ActiveControl.Left));
                        break;       

                    case LabourCostCol.CalUnit:
                        strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("imUnit");
                        strCaption = "";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value.ToString();
                        strFindField = "Unit";
                        
                        break;
                    case LabourCostCol.CutType:
                        strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmCutType");
                        strCaption = "分切方式选择";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value.ToString();
                        strFindField = "CutTimes";                                           
                        break;

                    case LabourCostCol.ItemNo:
                        strSQL = BaseFunctions.GetLookUpSQL ("iminvmaster") ;//" select ItemNo,ItemName,SupNo,SupName,MarketCost,CostUnit from iminvmaster where ClosedStatus=0 order by itemno";
                        strCaption = "物料选择";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value.ToString();
                        strFindField = "ItemNo";
                        break;
                }
            }
            if (strSQL == "") return;
            if (mblnLookUpSortByDescription)
            {
                strSQL = DataFunctions.GetSqlByDescriptionSort(strSQL);
                mblnLookUpSortByDescription = false;
            }

            DtlLookup(iColumnIndex, strSQL, strCaption, strFindValue, strFindField,"", strGridName);
        }

        private void DtlLookup(int iColumnIndex, string strSQL, string strCaption, string strFindValue, string strFindField, string strMenuName, string strGridName)
        {
            frmLookUp frmlookup = new frmLookUp(strSQL, strCaption, strFindValue, strFindField);
            frmlookup.ShowDialog();

            if (frmlookup.HaveReturnValue)
            {
                if (strGridName == this.dgvBOM.Name)
                {
                    switch ((DtlCol)iColumnIndex)
                    {
                        case DtlCol.WKName:
                            if (strMenuName == this.可更改工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WkName");
                                //this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else if (strMenuName == this.类别工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                            }
                            else if (strMenuName == this.所有工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WorkingProcedureName");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }                            
                            break;
                        case DtlCol.ItemNo:
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value = frmlookup.GetReturnValue("FItemID");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = frmlookup.GetReturnValue("ItemNo");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value = frmlookup.GetReturnValue("ItemName");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value = frmlookup.GetReturnValue("SupNo");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value = frmlookup.GetReturnValue("SupName");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value = frmlookup.GetReturnValue("MarketCost");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value = frmlookup.GetReturnValue("CostUnit");
                            break;
                    }
                }
                else if (strGridName == this.dgvLabourCost.Name)
                {
                    switch ((LabourCostCol)iColumnIndex)
                    {
                        case LabourCostCol.WKName:
                            if (strMenuName == this.可更改工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WkID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WkName");
                                //this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else if (strMenuName == this.类别工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WKID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                            }
                            else if (strMenuName == this.所有工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WorkingProcedureID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WorkingProcedureName");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            break;
                        case LabourCostCol.CalUnit:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value = frmlookup.GetReturnValue("Unit");
                            break;
                        case LabourCostCol.CutType:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value = frmlookup.GetReturnValue(strFindField);
                            break;
                        case LabourCostCol.ItemNo:
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = frmlookup.GetReturnValue("FItemID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = frmlookup.GetReturnValue("ItemNo");
                            }
                            break;
                    }
                }
            }
            frmlookup.Close();
        }


        private void dgvBOM_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvBOM.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)DtlCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvBOM") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell(e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvBOM_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvBOM.CurrentRow != null && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvBOM") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow(ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void dgvBOM_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven || e.ColumnIndex == (int)DtlCol.ValueChanged || e.ColumnIndex == (int)DtlCol.DelButton) return;
            dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value = "1";
            m_bDtlChanged = true;
            dgvBOM.EndEdit();
            if (e.ColumnIndex == (int)DtlCol.WKID)
            {
                string strWKID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value);
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKID + "'");
            }
            if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKID='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) + "'");
                if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) == "")
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureID", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)DtlCol.ItemNo)
            {
                if (DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "'") != "")
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value = DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)DtlCol.FItemID)
            {
                string strFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
                string strSQL = "select * from iminvmaster where FItemID='" + strFItemID + "'";
                DataRow drItemInfo = mdbcon.GetDataFirstRow(strSQL);
                if (drItemInfo != null)
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = CvtFunc.ToString(drItemInfo["itemno"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value = CvtFunc.ToString(drItemInfo["itemname"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value = CvtFunc.ToString(drItemInfo["SupNo"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value = CvtFunc.ToString(drItemInfo["SupName"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value = CvtFunc.ToString(drItemInfo["MarketCost"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value = CvtFunc.ToString(drItemInfo["CostUnit"]);
                }
            }
            dgvBOM.EndEdit();
        }

        private void dgvBOM_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvBOM.CurrentCell.Selected = false;
            }
            if (this.dgvBOM.CurrentRow == null) return;
            ShowFormula(this.dgvBOM.CurrentRow.Index);
        }

        private void dgvBOM_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvBOM.CurrentCell.Selected = false;
            }
        }

        private void dgvBOM_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvBOM.EndEdit();

            if (e.ColumnIndex == (int)DtlCol.Price || e.ColumnIndex == (int)DtlCol.PriceUnit || e.ColumnIndex == (int)DtlCol.ItemNo
                || e.ColumnIndex == (int)DtlCol.Qty || e.ColumnIndex == (int)DtlCol.WastageRate || e.ColumnIndex == (int)DtlCol.LabourCost)
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow(ref strErrMsg))
                {
                    Update_Detail(this.dgvBOM.Rows[e.RowIndex]);
                }
            }
            if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKProductID='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) + "'");
            }
            else if (e.ColumnIndex == (int)DtlCol.Price)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.3");
            }
            else if (e.ColumnIndex == (int)DtlCol.Qty)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = CvtFunc.ToDouble(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).ToString ("F8") ;
            }
            else if (e.ColumnIndex == (int)DtlCol.WastageRate)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)DtlCol.LabourCost)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.4");
            }
            else if (e.ColumnIndex == (int)DtlCol.DetailCost)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.4");
            }
        }

        private void dgvBOM_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void dgvBOM_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvBOM, e, (int)DtlCol.DelButton);
            //if (this.formStatus == FormStatus.Query)
            //{
            //    dgvBOM.Enabled = false;
            //    return;
            //}
            string strErrMsg = "";
            if (dgvBOM.CurrentRow != null && CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    //ShowLabourCost();
                }
                else
                {
                    return;
                }
            }
           
        }

        private void dgvBOM_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvBOM.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvBOM.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }

        private bool dgvBOM_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvBOM.EndEdit();
                    if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow(ref strErrMsg))
                            {

                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvBOM.CurrentCell.RowIndex < dgvBOM.Rows.Count - 1)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvBOM.CurrentCell.RowIndex > 0)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            if (dgvBOM.CurrentCell.RowIndex > 0)
                            {
                                dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                            }
                        }
                        else if (dgvBOM.Rows.Count > 1)
                        {

                            this.dgvBOM.Rows.Remove(this.dgvBOM.CurrentRow);
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvBOM.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvBOM);
                    if (dgvBOM.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow(ref strErrMsg))
                                {
                                    if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvBOM.CurrentCell.RowIndex < dgvBOM.Rows.Count - 1)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvBOM, dgvBOM.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }

        private void dgvBOM_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if (e.ColumnIndex ==(int)DtlCol.WKName && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dgvBOM.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        if (e.RowIndex < dgvBOM.Rows.Count - 1 && dgvBOM.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            if (e.RowIndex > 0 && dgvBOM.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString())
                            { }
                            else
                            {
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }

        #endregion


        #region LabourCost

        private void dgvLabourCost_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvLabourCost.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (int.Parse(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value.ToString()) > 0 && int.Parse(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvLabourCost") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven_LabourCost)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell_LabourCost (e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvLabourCost_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvLabourCost.CurrentRow != null && int.Parse(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value.ToString()) > 0 && int.Parse(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvLabourCost") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven_LabourCost )
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow_LabourCost (ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void dgvLabourCost_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven_LabourCost || e.ColumnIndex == (int)LabourCostCol.ValueChanged || e.ColumnIndex == (int)DtlCol.DelButton) return;
            dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ValueChanged].Value = "1";
            m_bDtlChanged_LabourCost  = true;
            dgvLabourCost.EndEdit();
            if (e.ColumnIndex == (int)LabourCostCol.WKID)
            {
                string strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                string strWKName =CvtFunc.ToString ( this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKProductID='" + strWKID + "'");
                if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) <= 0)
                {
                    double dblWorkCost = DataFunctions.GetCategoryWKWorkCost(txtCategoryID.Text, strWKID);
                    if (dblWorkCost > 0)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dblWorkCost, "Ns.2");
                    }
                }
            }
            if (e.ColumnIndex == (int)LabourCostCol.WKName)
            {
                if (CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value) == "")
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureID", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) + "'");
                }
            }
            else if (e.ColumnIndex == (int)LabourCostCol.CutType)
            {
                string strCutType = CvtFunc.ToString ( this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.CutType].Value) ;
                double dblCutType = CvtFunc.ToDouble ( DataFunctions.GetFieldValue ( "rmCutType","CutTimes","CutType='"+ strCutType +"'"));
                if (dblCutType == 0 )
                {
                    dblCutType = CvtFunc.ToDouble(strCutType);
                }
                double dblWorkQty = CvtFunc.ToDouble(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkQty].Value);
                if (dblWorkQty != 0)
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(dblWorkQty / dblCutType, "ns.0");
                else
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.TotalQty].Value = "0";
            }
            else if (e.ColumnIndex == (int)LabourCostCol.ItemNo)
            {
                if (DataFunctions.GetFieldValue("iminvmaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value) + "'") != "")
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)LabourCostCol.FItemID)
            {
                string strFItemID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = DataFunctions.GetFieldValue("iminvmaster", "itemno", "FItemID='" + strFItemID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strFItemID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strFItemID + "'");
            }
            dgvLabourCost.EndEdit();
        }

        private void dgvLabourCost_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                this.dgvLabourCost.CurrentCell.Selected = false;
            }
            if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
            {
                this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = true;
            }
        }

        private void dgvLabourCost_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                this.dgvLabourCost.CurrentCell.Selected = false;
            }
        }

        private void dgvLabourCost_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvLabourCost.EndEdit();
            if (e.ColumnIndex == (int)LabourCostCol.WorkQty || e.ColumnIndex == (int)LabourCostCol.CutType)
            {
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotalQty].Value =BaseFunctions.FormatNumeric(  CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value) / CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value),"Ns.2");

            }
            if (e.ColumnIndex == (int)LabourCostCol.WorkQty)
            {
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value, "Ns.2");
            }
            if (e.ColumnIndex == (int)LabourCostCol.WKName)
            {
                if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) <= 0)
                {
                    double dblWorkCost = DataFunctions.GetCategoryWKWorkCost(txtCategoryID.Text, CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value));
                    if (dblWorkCost > 0)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dblWorkCost, "Ns.2");
                    }
                }
            }
            if (e.ColumnIndex == (int)LabourCostCol.CalUnit || e.ColumnIndex == (int)LabourCostCol.CutType || e.ColumnIndex == (int)LabourCostCol.StandardQty
                || e.ColumnIndex == (int)LabourCostCol.UsedHours  || e.ColumnIndex == (int)LabourCostCol.UnitCost || e.ColumnIndex == (int)LabourCostCol.WorkCost 
                || e.ColumnIndex == (int)LabourCostCol.TotalQty  || e.ColumnIndex== (int) LabourCostCol.WorkQty || e.ColumnIndex  == (int) LabourCostCol.WKName )
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow_LabourCost (ref strErrMsg))
                {
                    Update_Detail_LabourCost (this.dgvLabourCost.Rows[e.RowIndex]);
                }
            }
            if (e.ColumnIndex == (int)LabourCostCol.StandardQty )
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value, "ns.2"); 
            }
            else if (e.ColumnIndex == (int)LabourCostCol.StandardWage)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.StandardWage26)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.TotalQty)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.UsedHours)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.UnitCost)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.8");
            }
        }

        private void dgvLabourCost_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void dgvLabourCost_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvLabourCost, e, (int)LabourCostCol.DelButton);
            //if (this.formStatus == FormStatus.Query)
            //{
            //    dgvLabourCost.Enabled = false;
            //    return;
            //}
            string strErrMsg = "";
            if (dgvLabourCost.CurrentRow != null && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow_LabourCost (ref strErrMsg))
                {
                    if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

        }

        private void dgvLabourCost_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvLabourCost.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvLabourCost.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }

        private bool dgvLabourCost_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvLabourCost.EndEdit();
                    if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow_LabourCost(ref strErrMsg))
                            {

                                if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvLabourCost.CurrentCell.RowIndex < dgvLabourCost.Rows.Count - 1)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex + 1].Cells[(int)LabourCostCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow_LabourCost (ref strErrMsg))
                        {
                            if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow_LabourCost (ref strErrMsg))
                            {
                                if (!Update_Detail_LabourCost  (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvLabourCost.CurrentCell.RowIndex > 0)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex - 1].Cells[(int)LabourCostCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow_LabourCost (ref strErrMsg))
                        {
                            if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            if (dgvLabourCost.CurrentCell.RowIndex > 0)
                            {
                                dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex - 1].Cells[(int)LabourCostCol.WKName];
                            }
                        }
                        else if (dgvLabourCost.Rows.Count > 1)
                        {

                            this.dgvLabourCost.Rows.Remove(this.dgvLabourCost.CurrentRow);
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvLabourCost.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvLabourCost);
                    if (dgvLabourCost.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow_LabourCost (ref strErrMsg))
                                {
                                    if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow_LabourCost (ref strErrMsg))
                            {
                                if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvLabourCost.CurrentCell.RowIndex < dgvLabourCost.Rows.Count - 1)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex + 1].Cells[(int)LabourCostCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvLabourCost, dgvLabourCost.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }



        private void dgvLabourCost_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if (e.ColumnIndex == (int)LabourCostCol.WKName  && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dgvLabourCost.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        if (e.RowIndex < dgvLabourCost.Rows.Count - 1 && dgvLabourCost.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            if (e.RowIndex > 0 && dgvLabourCost.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString())
                            { }
                            else
                            {
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }


        #endregion

        private void btnTallyCalculate_Click(object sender, EventArgs e)
        {
            string strSQL= string.Empty ;
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                if (!this.Update_Detail(dgvBOM.CurrentRow)) return;
                if (this.dgvBOM.CurrentRow == null) return;
                if (this.dgvBOM.CurrentCell == null) return;
                if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
                string strRecID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, frmRMWKFormula.FormulaType.FromProductBOM);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                frmCal.Text = "定额数量  计算公式选择： " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "    " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
                frmCal.ShowDialog();
                strSQL = "select * from rmProductBOMDetail where RecID='" + strRecID + "'";
               
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                if (this.dgvLabourCost.CurrentRow == null) return;
                if (this.dgvLabourCost.CurrentCell == null) return;
                this.dgvLabourCost.EndEdit();
                if (!this.Update_Detail_LabourCost ( dgvLabourCost.CurrentRow )) return ;
                string strRecID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, frmRMWKFormula.FormulaType.OtherProductBOM);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                frmCal.Text = "项目分摊  计算公式选择： " + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) + "    " + txtProductName.Text;
                frmCal.ShowDialog();
                strSQL = "select * from rmProductBOMLabourCost where RecID='" + strRecID + "'";
               
            }

            if (this.tbcMain.SelectedTab  == tbpBOM)
            {
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.UpdateCost(mdbcon, drRow);

                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Qty].Value = drRow["Qty"];
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.TotalCost].Value = drRow["TotalCost"];
                this.dgvBOM.EndEdit();
                this.dgvBOM.RefreshEdit();
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.UpdateLabourCostDetail(mdbcon, drRow);
                if (drRow != null)
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value = drRow["WorkQty"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotalQty].Value = drRow["TotalQty"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotWorkCost].Value = drRow["DetailTotWorkCost"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.UsedHours].Value = drRow["SpendHours"];
                    this.dgvLabourCost.EndEdit();
                    this.dgvLabourCost.RefreshEdit();
                }
            }
            ShowFormula(this.dgvBOM.CurrentRow.Index);
        }

        private void ToAllVersionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab != tbpBOM) return; 
            if (this.dgvBOM.CurrentRow == null) return;
            if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
            if (CvtFunc.ToDouble  (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value ) <=0) return ;
            string strOldFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
            string strOldItemNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
            string strOldSupNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value); 
            Dtl_LookUp( (int)DtlCol.ItemNo , this.dgvBOM.Name.ToString());
            UpdateDetailByNewItemNo(true, strOldFItemID, strOldSupNo);
        }


        private void UpdateDetailByNewItemNo(bool blnVerClosed, string strOldFItemID, string strOldSupNo)
        {

            RMProductBOMRevDAL rmDAL = new RMProductBOMRevDAL();
            string strItemFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
            string strItemNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
            string strSupNo=CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value);
            string strSQL = "select * from rmProductBOMDetail where FItemID='" + strOldFItemID + "' and supno='" + strOldSupNo + "' " + (blnVerClosed ? "" : "and ProductFItemID in ( select ProductFItemID from rmProductBOMRev where VerClosed=0)") + " ";
            DataTable dtBOM = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drBOM in dtBOM.Rows)
            {
                drBOM["SupNo"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value;
                drBOM["SupName"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value;
                drBOM["FItemID"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value;  
                drBOM["ItemNo"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value;
                drBOM["Price"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value;
                drBOM["PriceUnit"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value; 
                rmDAL.UpdateBOMDetail(mdbcon, drBOM);
            }            
        }

        private void ToOpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab != tbpBOM) return;
            if (this.dgvBOM.CurrentRow == null) return;
            if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
            if (CvtFunc.ToDouble(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) <= 0) return;
            string strOldItemFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
            string strOldSupNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value);
            Dtl_LookUp((int)DtlCol.ItemNo, this.dgvBOM.Name.ToString());
            UpdateDetailByNewItemNo(false, strOldItemFItemID, strOldSupNo);
        }

        private void btnCopyTo_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew) return;
            RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                frmRMProductBOMCopy frmCopy = new frmRMProductBOMCopy(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text);
                bool blnSuccess = false;
                string strCategoryID = "";
                string strSetID ="";
                string strProductFItemID="";
                string strTechnicsName = "";
                frmCopy.CopyTo(ref blnSuccess, ref strCategoryID, ref strSetID, ref strProductFItemID,ref strTechnicsName);

                if (blnSuccess == false) return;

                dbcon.BeginTran();
                string strRecID = CvtFunc.ToString(this.dgList.CurrentRow.Cells["RecID"].Value);
                DataRow drHdr = dbcon.GetDataFirstRow("select * from rmProductBOMHdr where ProductFItemID='" + txtProductFItemID.Text + "' and TechnicsName='"+ txtTechnicsName.Text +"'");

                if (rmDAL.CopyTo(dbcon, drHdr, strCategoryID,strSetID ,strProductFItemID,strTechnicsName))
                {
                    dbcon.CommitTran();
                    this.dgList.RefreshData();
                    this.dgList.Focus();
                    MessageBox.Show("复制成功完成！", "PDM", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    dbcon.RollbackTran();
                }
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran();
                MsgBoxEx.Show(ex.ToString());
                return;
            }

            dbcon.CloseCon();
        }

        private void btnCopyBOMToLabour_Click(object sender, EventArgs e)
        {
            frmRMCopyBOMToLabourCost frmLabourCost = new frmRMCopyBOMToLabourCost();
            frmRMCopyBOMToLabourCost.Parameter para = new frmRMCopyBOMToLabourCost.Parameter();
            para.strCategoryName = txtCategoryName.Text;
            para.strSetName = txtSetName.Text;
            para.strProductName = txtProductName.Text;
            para.strTechnicsName = txtTechnicsName.Text;
            para.strCategoryID = txtCategoryID.Text;
            para.strSetID = txtSetID.Text;
            para.strProductFitemID = txtProductFItemID.Text;
 
            frmLabourCost.ShowFrom(frmRMCopyBOMToLabourCost.FromType.BOM , this.dgvBOM, para);
            if (frmLabourCost.mblnHasReturn)
            {
                foreach (DataGridViewRow dgvRow in frmLabourCost.dgvBOM.Rows)
                {
                    if (CvtFunc.ToBoolean(dgvRow.Cells["SEL"].Value))
                    {
                        
                        string strWKID = CvtFunc.ToString(dgvRow.Cells["WKID"].Value);
                        string strWKName = CvtFunc.ToString(dgvRow.Cells["WKName"].Value);
                        string strFItemID = CvtFunc.ToString(dgvRow.Cells["FItemID"].Value);
                        string strProductFItemID = CvtFunc.ToString(dgvRow.Cells["ProductFItemID"].Value);
                        string strItemNo = CvtFunc.ToString(dgvRow.Cells["ItemNo"].Value);
                        int intInsertRow = GetLastRowInGridForSpecilaWKName(strWKID);
                        string strErrMsg = "";
                        if (CheckDtlRow_LabourCost(ref strErrMsg))
                        {
                            AddDtlRow(this.dgvLabourCost.Name, intInsertRow);
                        }
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = CvtFunc.ToString(dgvRow.Cells["WKID"].Value );
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = strWKName;
                        this.dgvLabourCost_CellValueChanged(this.dgvLabourCost, new DataGridViewCellEventArgs((int)LabourCostCol.WKName, this.dgvLabourCost.CurrentCell.RowIndex));
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = strFItemID;
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = strItemNo;
                     
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strFItemID + "'");
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CategoryID].Value = txtCategoryID.Text;
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.SetID].Value = txtSetID.Text; 
                        this.Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow);
                    }
                }
            }
        }


        private int GetLastRowInGridForSpecilaWKName(string strWKID)
        {
            bool blnFind = false;
            foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
            {
                if (CvtFunc.ToString(dgvRow.Cells["WKID"].Value) == strWKID)
                {
                    blnFind = true;
                }
                else
                {
                    if (blnFind) return dgvRow.Index;
                }
            }
            return this.dgvLabourCost.Rows.Count - 1;

        }

        private void ShowWorkCost()//计算关键工序的成本
        {

            string strSQL = "select sum(DetailCost),sum(DetailTotWorkCost) from rmProductBOMLabourCost where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}' and IsKeyWK=1";
            strSQL = string.Format(strSQL, txtCategoryID.Text , txtSetID.Text ,  txtProductFItemID.Text,txtTechnicsName.Text);
            DataRow  drTotal = mdbcon .GetDataFirstRow(strSQL);
            if (drTotal != null)
            {              
                txtKeyWKWorkCost.Text  =BaseFunctions.FormatNumeric ( CvtFunc.ToDouble(drTotal[1]),"Ns.2");
            }
            txtOtherWorkCost.Text = BaseFunctions.FormatNumeric( CvtFunc.ToDouble(txtTotalWorkCost.Text) - CvtFunc.ToDouble ( txtKeyWKWorkCost.Text) , "Ns.2");
            txtTotalWorkCost2.Text = txtTotalWorkCost.Text;
        }
      

    }
}
